#include "keyboard.h"

#include <iostream>
#include <OISException.h>
#include <QSet>

Keyboard::Keyboard(QObject *parent)
  : InputDevice(parent), _keyboard(NULL)
{
}

void Keyboard::init(OIS::InputManager *manager)
{
  try
  {
    _keyboard = (OIS::Keyboard*)manager->createInputObject(OIS::OISKeyboard, true);
    _keyboard->setEventCallback(this);
  }
  catch(OIS::Exception &ex)
  {
    std::cout << "\nException raised on keyboard creation: " << ex.eText << std::endl;
    _keyboard = NULL;
  }
}

bool Keyboard::keyPressed(const OIS::KeyEvent &arg)
{
  switch (arg.key)
  {
  case 200:
    _currentKey = Ak_Up;
    break;
  case 208:
    _currentKey = Ak_Down;
    break;
  case 203:
    _currentKey = Ak_Left;
    break;
  case 205:
    _currentKey = Ak_Right;
    break;
  case 28:
    emit key(Ak_Enter);
    break;
  case 14:
    emit key(Ak_Back);
    break;
  }
  if ((QSet<int>() << 200 << 208 << 203 << 205).contains(arg.key))
  {
    startKeyEmit();
  }
  return true;
}

bool Keyboard::keyReleased(const OIS::KeyEvent &arg)
{
  if (arg.key == 200 && _currentKey == Ak_Up ||
      arg.key == 208 && _currentKey == Ak_Down ||
      arg.key == 203 && _currentKey == Ak_Left ||
      arg.key == 205 && _currentKey == Ak_Right ||
      arg.key == 28 && _currentKey == Ak_Enter ||
      arg.key == 14 && _currentKey == Ak_Back)
    stopKeyEmit();
  return true;
}

void Keyboard::capture()
{
  if (_keyboard == NULL)
    return;
  _keyboard->capture();
}
